<template>
  <view class="Mall4j register">
    <view class="con">
      <!--			<image :src="uniLoginLogoImg" mode="heightFix" @tap="toIndex" />-->
      <view class="form-title">{{ i18n.userRegistration }}</view>
      <!-- 第一步 -->
      <block v-if="registerStep==1">
        <view class="login-form">
          <!--					<view :class="'item ' + (errorTips==1 || mobileEmpty? 'error':'')">-->
          <!--						&lt;!&ndash; 手机号 &ndash;&gt;-->
          <!--						<view class="account">-->
          <!--							<text class="input-item">+86</text>-->
          <!--							<input v-model="mobile" type="text" placeholder-class="inp-palcehoder"-->
          <!--								:placeholder="i18n.enterMobileNumber" maxlength="11" @focus="handleInpFocus"></input>-->
          <!--						</view>-->
          <!--						<view v-if="errorTips==1" class="error-text">{{ i18n.enterValidPhone }}</view>-->
          <!--						<view v-if="mobileEmpty" class="error-text">{{ i18n.enterMobileNumber }}</view>-->
          <!--					</view>-->
          <!--					<view :class="'item ' + (errorTips==2 || errorTips==6? 'error':'')">-->
          <!--						&lt;!&ndash; 验证码 &ndash;&gt;-->
          <!--						<view class="account">-->
          <!--							<input v-model="validCode" type="text" class="int-yzm" placeholder-class="inp-palcehoder"-->
          <!--								:placeholder="i18n.enterCode" maxlength="6" @focus="handleInpFocus"></input>-->
          <!--							<view v-if="show" class="input-item get-yzm" @tap="getCode">{{ i18n.getCode }}</view>-->
          <!--							<view v-if="!show" class="input-item get-yzm" @tap="getCode">{{ count }} s</view>-->
          <!--						</view>-->
          <!--						<view v-if="errorTips==2" class="error-text">{{ i18n.enterCode }}</view>-->
          <!--						<view v-if="errorTips==6" class="error-text">{{ i18n.enterCodeFirst }}</view>-->
          <!--					</view>-->
          <!-- 条款 -->
          <!--					<view class="item statement">-->
          <!--						<view class="statement-text">-->
          <!--							<label @tap.stop="handlePrivacyClick">-->
          <!--								<checkbox class="check-box" :checked="isPrivacy===1" />-->
          <!--								{{ i18n.haveReadAndAppgree }}-->
          <!--								<text @tap.stop="toService()">《{{ i18n.termsOfService }}》</text>-->
          <!--								<text style="color:#000">{{ i18n.and }}</text>-->
          <!--								<text @tap.stop="toPrivacy()">《{{ i18n.privacyPolicy }}》</text>-->
          <!--							</label>-->
          <!--						</view>-->
          <!--					</view>-->
          <!--					<view class="to-login-or-bind">-->
          <!--						<view v-if="appType<=2" class="to-bind-text">-->
          <!--							<text @tap="toLoginOrBind">{{ i18n.haveAnAccount }}{{ i18n.goToBind }}></text>-->
          <!--						</view>-->
          <!--						<view class="to-login-text" @tap="toLoginOrBind('login')">-->
          <!--							<text>{{ i18n.goToLogin }}></text>-->
          <!--						</view>-->
          <!--					</view>-->
          <form>
            <uni-forms ref="registerForm1" :modelValue="registerData" :rules="registerRules">
              <uni-forms-item label="手机号" name="mobile" required>
                <!--          <text class="form-input-text" > {{ "手机号 " }} </text>-->
                <input type="text" maxlength="11" style="position:  relative; top: 25rpx;" v-model="registerData.mobile" placeholder="手机号" />
              </uni-forms-item>
              <uni-forms-item class="input-items" label="验证码" name="validCode" required>
                <input style="position: relative; top: 25rpx; width: 100rpx;" type="text" class="form-input" v-model="registerData.validCode" placeholder="验证码" />
                <view class="codeBtn1" v-if="show" @tap="getCode(registerData.mobile)">获取验证码</view>
                <view class="codeBtn2" v-else>{{count}}</view>
              </uni-forms-item>
              <!-- 条款 -->
              <view class="item statement">
                <view class="statement-text">
                  <label @tap.stop="handlePrivacyClick">
                    <checkbox class="check-box" :checked="isPrivacy===1" />
                    {{ i18n.haveReadAndAppgree }}
                    <text @tap.stop="toService">《{{ i18n.termsOfService }}》</text>
                    <text style="color:#000">{{ i18n.and }}</text>
                    <text @tap.stop="toPrivacy">《{{ i18n.privacyPolicy }}》</text>
                  </label>
                </view>
              </view>
              <view class="to-login-or-bind other-opration">
                <view v-if="appType<=2" class="to-bind-text">
                  <text @tap="toLoginOrBind">{{ i18n.haveAnAccount }}{{ i18n.goToBind }}></text>
                </view>
                <view class="to-login-text" @tap="toLoginOrBind('login')">
                  <text>{{ i18n.goToLogin }}></text>
                </view>
              </view>
              <!--              <uni-forms-item class="input-items" label="新密码" name="newPassWord" required>-->
              <!--                <input type="password" class="form-input" v-model="registerData.newPassWord" placeholder="新密码" />-->
              <!--              </uni-forms-item>-->
              <!--              <uni-forms-item class="input-items" label="确认密码" name="comNewPassWord" required>-->
              <!--                <input type="password" class="form-input" v-model="registerData.comNewPassWord" placeholder="确认新密码" />-->
              <!--              </uni-forms-item>-->
            </uni-forms>
          </form>
          <view class="text-wrapper_5 flex-col" @click="registerNextBtnFun1">
            <text class="text_11">{{ i18n.nextStep }}</text>
          </view>
          <view class="text-wrapper_back flex-col" @tap="toIndex">
            <text class="text_11">{{ i18n.backHomepage }}</text>
          </view>
        </view>
        <!-- 按钮 -->
        <!--				<view>-->
        <!--					<button class="authorized-btn" @tap="registerNext">{{ i18n.nextStep }}</button>-->
        <!--					<button class="to-idx-btn" @tap="toIndex">{{ i18n.backHomepage }}</button>-->
        <!--				</view>-->
      </block>

      <!-- 第二步 -->
      <block v-if="registerStep==2">
        <view class="login-form">
          <!--					<view :class="['item',errorTips==11? 'error':'']">-->
          <!--						&lt;!&ndash; 设置昵称 &ndash;&gt;-->
          <!--						<view class="account">-->
          <!--							<text class="input-item">{{ i18n.setNickname }}</text>-->
          <!--							<input v-model="nickName" type="text" placeholder-class="inp-palcehoder"-->
          <!--								:placeholder="i18n.pleaseSetNickname" @focus="handleInpFocus"></input>-->
          <!--						</view>-->
          <!--						<view v-if="errorTips==11" class="error-text">{{ i18n.pleaseSetNickname }}</view>-->
          <!--					</view>-->
          <!--					<view :class="'item ' + (errorTips==3? 'error':'')">-->
          <!--						&lt;!&ndash; 设置账号 &ndash;&gt;-->
          <!--						<view class="account">-->
          <!--							<text class="input-item">{{ i18n.setAccountNumber }}</text>-->
          <!--							<input v-model="userName" type="text" placeholder-class="inp-palcehoder"-->
          <!--								:placeholder="i18n.pleaseSetAccount" @focus="handleInpFocus"></input>-->
          <!--						</view>-->
          <!--						<view v-if="errorTips==3" class="error-text">{{ i18n.setAccountNumberTips }}</view>-->
          <!--					</view>-->
          <!--					<view :class="'item ' + (errorTips? 'error':'')">-->
          <!--						&lt;!&ndash; 密码 &ndash;&gt;-->
          <!--						<view class="account">-->
          <!--							<text class="input-item">{{ i18n.setPassword }}</text>-->
          <!--							<input v-model="password" type="password" placeholder-class="inp-palcehoder"-->
          <!--								:placeholder="i18n.pleaseSetPassword" @focus="handleInpFocus"></input>-->
          <!--						</view>-->
          <!--						<view v-if="errorTips==4" class="error-text">{{ i18n.enterPassword }}</view>-->
          <!--						<view v-if="errorTips==9" class="error-text">{{ i18n.passwordVerification }}</view>-->
          <!--						<view v-if="errorTips==10" class="error-text">{{ i18n.enterNewPasswordTips }}</view>-->
          <!--					</view>-->
          <!--					<view :class="'item ' + (errorTips==5 || errorTips==7? 'error':'')">-->
          <!--						&lt;!&ndash; 确认密码 &ndash;&gt;-->
          <!--						<view class="account">-->
          <!--							<text class="input-item">{{ i18n.confirmNew }}</text>-->
          <!--							<input v-model="confirmPwd" type="password" placeholder-class="inp-palcehoder"-->
          <!--								:placeholder="i18n.enterPasswordAgain" @focus="handleInpFocus"></input>-->
          <!--						</view>-->
          <!--						<view v-if="errorTips==5" class="error-text">{{ i18n.confirmPasswordAgain }}</view>-->
          <!--						<view v-if="errorTips==7" class="error-text">{{ i18n.ConfirmPasswordNot }}</view>-->
          <!--					</view>-->
          <form>
            <uni-forms class="form-items" ref="registerForm2" :modelValue="registerData" :rules="registerRules">
              <uni-forms-item class="input-items" label="昵称" name="nickName" required>
                <input type="text" class="form-input" v-model="registerData.nickName" placeholder="昵称" />
              </uni-forms-item>
              <uni-forms-item class="input-items" label="用户名" name="userName" required>
                <input type="text" class="form-input" v-model="registerData.userName" placeholder="用户名" />
              </uni-forms-item>
              <uni-forms-item class="input-items" label="密码" name="password" required>
                <input type="password" class="form-input" v-model="registerData.password" placeholder="密码" />
              </uni-forms-item>
              <uni-forms-item class="input-items" label="确认密码" name="confirmPwd" required>
                <input type="password" class="form-input" v-model="registerData.confirmPwd" placeholder="确认密码" />
              </uni-forms-item>
            </uni-forms>
          </form>
          <view class="text-wrapper_5 flex-col" @click="registerNextBtnFun2">
            <text class="text_11">{{ i18n.nextStep }}</text>
          </view>
          <view class="text-wrapper_back flex-col" @tap="toIndex">
            <text class="text_11">{{ i18n.backHomepage }}</text>
          </view>
        </view>
        <!-- 按钮 -->
        <!--				<view>-->
        <!--					<button class="authorized-btn" @tap="registerNext">{{ i18n.nextStep }}</button>-->
        <!--					<button class="to-idx-btn" @tap="toIndex">{{ i18n.backHomepage }}</button>-->
        <!--				</view>-->
      </block>

      <!-- 第三步 -->
      <block v-if="registerStep==3">
        <view class="login-form">
          <view class="successful">{{ i18n.registrationSuccessful }}</view>
        </view>
        <!-- 按钮 -->
        <view>
          <!--					<button class="authorized-btn" @tap="toIndex">{{ i18n.backHomepage }}</button>-->

          <view class="text-wrapper_back flex-col" @tap="toIndex">
            <text class="text_11">{{ i18n.backHomepage }}</text>
          </view>
        </view>
      </block>

    </view>

    <privacy-pop v-if="showPop" @hidePop="hidePop" @confirm="popConfirm" />
  </view>
</template>

<script>
// pages/register/register.js
var http = require('../../utils/http')
var util = require('../../utils/util.js')
import {
  encrypt
} from '@/utils/crypto.js'
import privacyPop from '../../components/privacy-pop/index.vue'

export default {

  components: {
    privacyPop
  },
  props: {},
  data () {
    return {
      // 注册步骤
      registerStep: 1,
      // 输入错误提示:  1手机号输入错误  2验证码输入错误  3账号输入错误  4密码输入错误  5验证密码输入错误
      errorTips: 0,
      // 手机号
      mobile: '',
      // 验证码
      validCode: '',
      // 用户名
      userName: '',
      // 昵称
      nickName: '',
      // 密码
      password: '',
      // 确认密码
      confirmPwd: '',
      // 校验登陆注册验证码成功的标识
      checkRegisterSmsFlag: '',

      // 验证码相关
      show: true,
      count: '',
      timer: null,
      hadGotCode: false,
      isResting: false,
      // identical: Boolean, //是否一致
      // 号码是否为空
      mobileEmpty: false,
      uniLoginLogoImg: uni.getStorageSync('uniLoginLogoImg'),
      isPrivacy: uni.getStorageSync('isPrivacy') || 0,
      showPop: false,
      registerData: {
        mobile: '',
        validCode: '',
        userName: '',
        nickName: '',
        password: '',
        confirmPwd: ''
      },
      registerRules: {
        mobile: {
          rules: [
            {
              required: true,
              errorMessage: '请输入手机号',
              trigger: ['change', 'blur']
            },
            {
              minLength: 11,
              maxLength: 11,
              errorMessage: '长度为11位',
              trigger: ['change', 'blur']
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg = /^1[0-9]{10}$/
                if (!iphoneReg.test(value)) {
                  callback('格式不正确')
                }
                return true
              }
            }
          ]
        },
        validCode: {
          rules: [
            {
              required: true,
              errorMessage: '请输入验证码',
              trigger: ['change', 'blur']
            },
            {
              minLength: 6,
              maxLength: 6,
              errorMessage: '长度为6位',
              trigger: ['change', 'blur']
            }
          ]
        },
        nickName: {
          rules: [
            {
              required: true,
              errorMessage: '请输入昵称',
              trigger: ['change', 'blur']
            },
            {
              minLength: 5,
              errorMessage: '长度大于5位',
              trigger: ['change', 'blur']
            }
          ]
        },
        userName: {
          rules: [
            {
              required: true,
              errorMessage: '请输入用户名',
              trigger: ['change', 'blur']
            },
            {
              minLength: 5,
              errorMessage: '长度大于5位',
              trigger: ['change', 'blur']
            }
          ]
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: '请输入密码',
              trigger: ['change', 'blur']
            },
            {
              minLength: 6,
              maxLength: 16,
              errorMessage: '长度为6~16位',
              trigger: ['change', 'blur']
            }
          ]
        },
        confirmPwd: {
          rules: [
            {
              required: true,
              errorMessage: '请再次输入密码',
              trigger: ['change', 'blur']
            },
            {
              validateFunction: (rule, value, data, callback) => {
                if (this.registerData.password !== this.registerData.confirmPwd) {
                  callback('两次密码不一致')
                }
                return true
              }
            }
          ]
        }

      }
    }
  },

  computed: {
    i18n () {
      return this.$t('index')
    },
    appType () {
      return uni.getStorageSync('appType')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.weChatLogin()
    uni.setNavigationBarTitle({
      title: this.i18n.userRegistration
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.userRegistration
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
  methods: {

    /**
     * 弹窗确认
     */
    popConfirm (val) {
      this.isPrivacy = val
      this.showPop = false
    },
    /**
     * 弹窗取消
     */
    hidePop () {
      this.showPop = false
    },
    /**
     * 条款点击事件(勾选/取选)
     */
    handlePrivacyClick () {
      this.isPrivacy = this.isPrivacy === 1 ? 0 : 1
    },

    /**
     * 输入框聚焦
     */
    handleInpFocus () {
      this.errorTips = 0
    },

    /**
     * 获取验证码
     */
    getCode: function (e) {
      if (e && e === this.registerData.mobile) {
        this.mobile = this.registerData.mobile
      }
      if (!this.mobile) {
        this.setData({
          mobileEmpty: true,
          errorTips: 0
        })
        return
      }
      if (!util.checkPhoneNumber(this.mobile)) {
        this.setData({
          mobileEmpty: false,
          errorTips: 1
        })
        return
      }
      if (this.hadGotCode) {
        return
      }
      this.setData({
        mobileEmpty: false,
        errorTips: 0
      })
      var params = {
        url: '/user/sendRegisterSms',
        method: 'put',
        data: {
          mobile: this.mobile
        },
        callBack: res => {
          this.setData({
            hadGotCode: true
          })
          const timeCount = 60
          if (!this.timer) {
            let count = timeCount
            let timer = this.timer
            setTimeout(() => {
              this.setData({
                count: count,
                show: false
              })
            }, 1000)
            timer = setInterval(() => {
              if (count > 0 && count <= timeCount) {
                this.setData({
                  count: count--
                })
              } else {
                clearInterval(timer)
                this.setData({
                  timer: null,
                  show: true,
                  hadGotCode: false
                })
              }
            }, 1000)
          }
        }
      }
      http.request(params)
    },
    registerNextBtnFun1 () {
      this.$refs.registerForm1.validate().then(res => {
        this.mobile = this.registerData.mobile
        this.validCode = this.registerData.validCode
        this.registerNext()
      }).catch(err => {
        uni.showToast({
          title: "数据错误,请重试",
          icon: 'none',
          duration: 1500
        })
      })
    },
    registerNextBtnFun2 () {
      this.$refs.registerForm2.validate().then(res => {
        this.userName = this.registerData.userName
        this.nickName = this.registerData.nickName
        this.password = this.registerData.password
        this.confirmPwd = this.registerData.confirmPwd
        this.registerNext()
      }).catch(err => {
        uni.showToast({
          title: "数据错误,请重试",
          icon: 'none',
          duration: 1500
        })
      })
    },
    /**
     * 注册-下一步按钮
     */
    registerNext () {
      if (!this.isPrivacy || this.isPrivacy === -1) {
        this.showPop = true
        return
      }
      // 注册第一步：校验验证码
      if (this.registerStep == 1) {
        this.checkValidCode()
        return
      }
      // 注册第二步：请求注册
      if (this.registerStep == 2) {
        this.registerOrBindUser()
      }
    },

    /**
     * 校验验证码
     */
    checkValidCode () {
      if (!this.mobile || this.mobile === '') {
        this.mobileEmpty = true
        this.errorTips = 0
        return
      }
      if (!util.checkPhoneNumber(this.mobile)) {
        this.mobileEmpty = false
        this.errorTips = 1
        return
      }
      if (!this.validCode.trim()) {
        this.errorTips = 2
        return
      }
      this.errorTips = 0
      // 校验验证码
      var params = {
        url: '/user/checkRegisterSms',
        method: 'put',
        data: {
          mobile: this.mobile,
          validCode: this.validCode
        },
        callBack: res => {
          const registerStep = this.registerStep += 1
          this.registerStep = registerStep
          this.checkRegisterSmsFlag = res
        }
      }
      http.request(params)
    },

    /**
     * 注册
     */
    registerOrBindUser () {
      // 校验用户填写的数据
      // 校验昵称
      if (!this.nickName || !this.nickName.trim()) {
        this.errorTips = 11
        return
      }
      // 校验用户名
      if (!util.checkUserName(this.userName)) {
        this.errorTips = 3
        return
      }
      // 校验密码 - 非空校验
      if (!this.password || !this.password.trim()) {
        this.errorTips = 4
        return
      }
      // 校验密码 - 密码格式
      if (!util.checkPassword(this.password)) {
        this.errorTips = 9
        return
      }
      // 校验确认密码
      if (!this.confirmPwd.trim()) {
        this.errorTips = 5
        return
      }
      // 确认密码与密码是否一致
      if (this.confirmPwd && this.password && (this.confirmPwd != this.password)) {
        this.errorTips = 7
        return
      }
      this.errorTips = 0
      // 请求注册
      var params = {
        url: '/user/register',
        method: 'POST',
        data: {
          checkRegisterSmsFlag: this.checkRegisterSmsFlag, // 校验登陆注册验证码成功的标识
          mobile: this.mobile,
          nickName: this.nickName,
          userName: this.userName,
          password: encrypt(this.password),
          tempUid: uni.getStorageSync('tempUidB2c')
        },
        callBack: res => {
          uni.hideLoading()
          let registerStep = this.registerStep
          registerStep += 1
          this.setData({
            registerStep
          })
          uni.setStorageSync('loginResult', res)
          uni.setStorageSync('token', res.accessToken)
        }
      }
      http.request(params)
    },

    /**
     * 去登录或绑定账号
     * @param {string} type login登录  否则为绑定
     */
    toLoginOrBind (type) {
      uni.redirectTo({
        url: type === 'login' ? '/pages/account-login/account-login' :
          '/pages/binding-phone/binding-phone'
      })
    },
    toService () {
      // uni.navigateTo({
      // 	url: "/pages/service-page/service-page"
      // })
      uni.navigateTo({
        url: "/pages/web-view/web-view?url=https://mall-app.cqone.cn/#/service?head=none"
      })
    },
    toPrivacy () {
      // uni.navigateTo({
      // 	url: "/pages/privacy_page/privacy_page"
      // })
      uni.navigateTo({
        url: "/pages/web-view/web-view?url=https://mall-app.cqone.cn/#/privacy?head=none"
      })
    },

    /**
     * 回到首页
     */
    toIndex: function () {
      this.$Router.pushTab('/pages/index/index')
    }
  }
}
</script>
<style scoped lang="scss">
@import "./register.css";
@import "./register.scss";
</style>
